package com.example.sociamedia.post.controller;

import com.example.sociamedia.post.dto.CommentRequest;
import com.example.sociamedia.post.dto.CommentResponse;
import com.example.sociamedia.post.entity.Comment;
import com.example.sociamedia.post.mapper.CommentMapper;
import com.example.sociamedia.user.entity.User;
import com.example.sociamedia.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.Timestamp;
import java.util.List;

@Service
public class CommentService implements CommentApi {
    private final CommentMapper commentMapper;
    private final UserMapper userMapper;

    @Autowired
    public CommentService(CommentMapper commentMapper, UserMapper userMapper) {
        this.commentMapper = commentMapper;
        this.userMapper = userMapper;
    }

    @Override
    public CommentResponse addComment(String sessionToken, CommentRequest request) {
        User user = userMapper.selectUserByToken(sessionToken);
        CommentResponse resp = new CommentResponse();
        if (user == null) {
            resp.setSuccess(false);
            resp.setMessage("无效的用户token");
            return resp;
        }
        if (request.getContent() == null || request.getContent().trim().isEmpty()) {
            resp.setSuccess(false);
            resp.setMessage("评论内容不能为空");
            return resp;
        }
        Comment comment = new Comment();
        comment.setPostId(request.getPostId());
        comment.setUserId(user.getUserid());
        comment.setContent(request.getContent());
        comment.setParentId(request.getParentId());
        commentMapper.insertComment(comment);
        resp.setSuccess(true);
        resp.setMessage("评论成功");
        resp.setCommentId(comment.getCommentId());
        resp.setPostId(comment.getPostId());
        resp.setUserId(comment.getUserId());
        resp.setContent(comment.getContent());
        resp.setCreatedAt(new Timestamp(System.currentTimeMillis()));
        resp.setParentId(comment.getParentId());
        return resp;
    }

    @Override
    public List<Comment> getCommentsByPost(Long postId) {
        return commentMapper.selectCommentsByPost(postId);
    }

    @Override
    public CommentResponse deleteComment(String sessionToken, Long commentId) {
        User user = userMapper.selectUserByToken(sessionToken);
        CommentResponse resp = new CommentResponse();
        if (user == null) {
            resp.setSuccess(false);
            resp.setMessage("无效的用户token");
            return resp;
        }
        int count = commentMapper.deleteComment(commentId, user.getUserid());
        if (count > 0) {
            resp.setSuccess(true);
            resp.setMessage("删除评论成功");
        } else {
            resp.setSuccess(false);
            resp.setMessage("只能删除自己的评论或评论不存在");
        }
        return resp;
    }
} 